package org.zhaolei.controller;

import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.zhaolei.controller.req.AccountLoginReq;
import org.zhaolei.controller.req.AccountRegisterReq;
import org.zhaolei.controller.req.FileUploadReq;
import org.zhaolei.dto.AccountDTO;
import org.zhaolei.interceptor.LoginInterceptor;
import org.zhaolei.service.AccountFileService;
import org.zhaolei.service.AccountService;
import org.zhaolei.util.JsonData;
import org.zhaolei.util.JwtUtil;

@RestController
@RequestMapping("/api/account/v1")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @Autowired
    private AccountFileService accountFileService;

    /**
     *  注册接口
     * @param req
     * @return
     */
    @PostMapping("register")
    public JsonData register(@RequestBody AccountRegisterReq req) {
        accountService.register(req);
        return JsonData.buildSuccess();
    }

    /**
     * 上传头像接口
     * @param file
     * @return
     */
    @PostMapping("upload_avatar")
    public JsonData uploadAvatar(@RequestParam("file") MultipartFile file) {
        String url = accountService.uploadAvatar(file);
        return JsonData.buildSuccess(url);
    }

    /**
     * 登录接口
     * @param req
     * @return
     */
    @PostMapping("login")
    public JsonData login(@RequestBody AccountLoginReq req) {
        AccountDTO accountDTO = accountService.login(req);
        //生成token jwt ssm  一般前端存储在localStorage里面，或 sessionStorage里面
        String token = JwtUtil.geneLoginJWT(accountDTO);

        return JsonData.buildSuccess(token);
    }

    /**
     * 获取用户详情接口
     * @return
     */
    @GetMapping("detail")
    public JsonData detail() {
        Long accountId = LoginInterceptor.threadLocal.get().getId();

        AccountDTO accountDTO = accountService.queryDetail(accountId);

        return JsonData.buildSuccess(accountDTO);
    }

    @PostMapping("upload")
    @Operation(summary = "普通小文件上传", description = "普通小文件上传")
    public JsonData upload(FileUploadReq req) {
        req.setAccountId(LoginInterceptor.threadLocal.get().getId());
        accountFileService.fileUpload(req);
        return JsonData.buildSuccess();
    }
}
